package com.zn.loading
{
    import deng.fzip.FZip;
    import deng.fzip.FZipFile;
    
    import flash.events.Event;
    import flash.events.IOErrorEvent;
    import flash.events.ProgressEvent;
    import flash.utils.ByteArray;

    public class ZipLoader extends LoaderItem
    {
        private var _fzip:FZip;

        _activeTypes("ZipLoader", ZipLoader);

        public function ZipLoader(url:String = null, name:String = null)
        {
            super(url, name);
        }

        protected override function init():void
        {
            super.init();

            _fzip = new FZip();
            _fzip.addEventListener(Event.COMPLETE, completeHandler);
            _fzip.addEventListener(ProgressEvent.PROGRESS, progressHandler);
            _fzip.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
        }

        protected override function completeHandler(event:Event):void
        {
            super.completeHandler(event);

            _content = _fzip;

            loaderStatus = LoaderStatus.COMPLETED;
            dispatchEvent(new LoaderEvent(LoaderEvent.COMPLETE,this));
        }

        public override function load(flush:Boolean = false):void
        {
            if (loaderStatus != LoaderStatus.READY && !flush)
                return;

            super.load(flush);

            _fzip.load(_urlRequest);
        }

        public function getDataByName(name:String):ByteArray
        {
            var file:FZipFile = _fzip.getFileByName(name);
            if (file)
                return file.content;
            return null;
        }

        public function getStrByName(name:String):String
        {
            var file:FZipFile = _fzip.getFileByName(name);
            if (file)
                return file.getContentAsString();
            return null;
        }

        override public function unload():void
        {
            super.unload();
            if (_fzip)
            {
                LoaderMax.removeLoaderItem(name, false);
                try
                {
                    _fzip.close();
                }
                catch (error:Error)
                {

                }

                _fzip = null;
            }
        }

     override public function stop():void
        {
            super.stop();
            if (_fzip)
			{
				try
				{
					_fzip.close();
				} 
				catch(error:Error) 
				{
					
				}
			}
        }
		
		public override function pause():void
		{
			super.pause();
			
			if (_fzip)
			{
				try
				{
					_fzip.close();
				} 
				catch(error:Error) 
				{
					
				}
			}
		}
    }
}
